var path=require('path');
var bodyParser=require('body-parser');
var app=require('express')();
var mongoose=require('mongoose');
var Attendance=require('./attendance.js');
mongoose.connect('mongodb://localhost/attendance');

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(bodyParser());
app.listen(3022,()=>{
    console.log('===============Port 3022',new Date());
});

app.get('/search',(req,res)=>{
    var end=new Date(),start=new Date(end.getFullYear(),end.getMonth()-1,end.getDate());
    res.render('search',{
        start:start,
        end:end,
        group:null
    });
});


app.post('/search',(req,res)=>{
    var body=req.body,now=new Date();
    console.log('body:',body);

    var start=new Date(body.startYear,body.startMonth-1,body.startDay);
    start=isNaN(start)?new Date(now.getFullYear(),now.getMonth()-1,now.getDate()):start;
    console.log('start date:',start);

    var end=new Date(body.endYear,body.endMonth-1,+body.endDay);
    end=isNaN(end)?new Date(now.getFullYear(),now.getMonth()-1,now.getDate()):end;
    console.log('end date:',end);

    Attendance.find({time:{$gte:start,$lte:new Date(end.getTime()+1000*3600*24)}},(err,data)=>{
        if(err)throw err;
        var group={};
        for(var row of data){
            var time=row.time;
            var local=time.toLocaleString().split(' ')[0];
            if(group[local]){
                group[local].push(row);
            }else{
                group[local]=[row];
            }
        }

        res.render('search',{
            start:start,
            end:end,
            group:group
        });
    });
});